package com.agh.portal.web;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.agh.portal.domain.Ad;
import com.agh.portal.domain.Student;
import com.agh.portal.domain.enumeration.AdvertisementCategory;
import com.agh.portal.domain.util.CustomDateUtils;
import com.agh.portal.service.DataService;
import com.agh.portal.service.SecurityUtils;

@RequestMapping("/ads")
@Controller
@RooWebScaffold(path = "ads", formBackingObject = Ad.class)
@RooWebFinder
public class AdController {
	
	@Autowired
	SecurityUtils secUtils;

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Ad ad, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
		if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, ad);
            return "ads/create";
        }
        uiModel.asMap().clear();
        ad.setCreationDate(new Date());
        ad.setStudent(secUtils.getLoggedStudent());
        ad.persist();
        return "redirect:/ads/" + encodeUrlPathSegment(ad.getId().toString(), httpServletRequest);
    }

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Ad());
        return "ads/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("ad", Ad.findAd(id));
        uiModel.addAttribute("itemId", id);
        return "ads/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(
    		@RequestParam(value = "page", required = false) Integer page, 
    		@RequestParam(value = "size", required = false) Integer size,
    		@RequestParam(value = "category", required = false) String category,
    		@RequestParam(value = "sortFieldName", required = false) String sortFieldName,
    		@RequestParam(value = "sortOrder" , required = false) String sortOrder,
    		Model uiModel) {
		if (page != null || size != null || category != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            AdvertisementCategory adCategory = AdvertisementCategory.parseEnum(category);
            sortFieldName = sortFieldName == null ? "creationDate" : sortFieldName;
            sortOrder = sortOrder == null ? "desc" : sortOrder;
          
            if(adCategory != null){
            	uiModel.addAttribute("ads", DataService.parseAdsToDataComponent(Ad.findAdEntriesByCategory(adCategory, firstResult, sizeNo, sortFieldName, sortOrder).getResultList()));
            }else{
            	uiModel.addAttribute("ads", DataService.parseAdsToDataComponent(Ad.findAdEntries(firstResult, sizeNo, sortFieldName, sortOrder)));
            }
            
            float nrOfPages = (float) Ad.countAds() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("ads", DataService.parseAdsToDataComponent(Ad.findAllAds()));
        }
        addDateTimeFormatPatterns(uiModel);
        return "ads/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Ad ad, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, ad);
            return "ads/update";
        }
        uiModel.asMap().clear();
        ad.merge();
        return "redirect:/ads/" + encodeUrlPathSegment(ad.getId().toString(), httpServletRequest);
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, Ad.findAd(id));
        return "ads/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Ad ad = Ad.findAd(id);
        ad.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/ads";
    }
	
	@RequestMapping(params = { "find=ByCategory", "form" }, method = RequestMethod.GET)
    public String findAdsByCategoryForm(Model uiModel) {
        uiModel.addAttribute("advertisementcategorys", java.util.Arrays.asList(AdvertisementCategory.class.getEnumConstants()));
        return "ads/findAdsByCategory";
    }

	@RequestMapping(params = { "find=ByCreationDateBetween", "form" }, method = RequestMethod.GET)
    public String findAdsByCreationDateBetweenForm(Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        return "ads/findAdsByCreationDateBetween";
    }

	@RequestMapping(params = { "find=ByStudent", "form" }, method = RequestMethod.GET)
    public String findAdsByStudentForm(Model uiModel) {
        uiModel.addAttribute("students", Student.findAllStudents());
        return "ads/findAdsByStudent";
    }

	@RequestMapping(params = { "find=ByTitleAndContentLike", "form" }, method = RequestMethod.GET)
    public String findAdsByTitleAndContentLikeForm(Model uiModel) {
        return "ads/findAdsByTitleAndContentLike";
    }

	@RequestMapping(params = { "find=ByTitleLike", "form" }, method = RequestMethod.GET)
    public String findAdsByTitleLikeForm(Model uiModel) {
        return "ads/findAdsByTitleLike";
    }

	void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("ad_creationdate_date_format", CustomDateUtils.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }

	void populateEditForm(Model uiModel, Ad ad) {
        uiModel.addAttribute("ad", ad);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("students", Student.findAllStudents());
        uiModel.addAttribute("advertisementcategorys", Arrays.asList(AdvertisementCategory.values()));
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }


}
